package com.david.musicapp.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import com.david.core.utils.CommonUtils
import com.david.musicapp.PlayService
import com.david.musicapp.R
import com.david.musicapp.bean.Song
import com.david.musicapp.utils.SongHelper
import com.david.musicapp.utils.SongUtils
import java.io.File

/**系统音乐选择项页面*/
class SystemSongActivity :BaseActivity(), PlayService.OnTimeProgressListener {
    var song: Song? = null
    var isSeekBarTouched = false

    private lateinit var musicName: TextView
    private lateinit var musicTime: TextView
    private lateinit var musicProgress: SeekBar
    private lateinit var musicPause: ImageView
    private lateinit var backToList: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_system_song)

        musicName = findViewById(R.id.music_name)
        musicTime = findViewById(R.id.music_time)
        musicProgress = findViewById(R.id.music_progress)
        backToList = findViewById(R.id.back_to_list)
        musicPause = findViewById(R.id.music_pause)

        val intent = intent
        val action = intent.action
        if (Intent.ACTION_VIEW == action) {
            val uri = intent.data
            val filePath: String? =
                CommonUtils.getMediaFilePathFromContentUri(uri, contentResolver)


            if (SongHelper.getInstance().getList().isNotEmpty()) {
                for (item in SongHelper.getInstance().getList()) {
                    if (filePath.equals(item.path)) {
                        SongHelper.getInstance().playMusic(item.id)
                        SongHelper.getInstance().currentId = item.id
                        song = item




                        if (filePath != null) {
                            musicName.text = filePath.substring(filePath.lastIndexOf("/") + 1)
                        }
                        musicProgress.max = song!!.duration/1000
                        musicTime.text = "00:00 / " + SongUtils.formatTime(musicProgress.max)

                        musicProgress.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
                            override fun onProgressChanged(
                                seekBar: SeekBar?,
                                progress: Int,
                                fromUser: Boolean
                            ) {

                            }

                            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                                isSeekBarTouched = true
                            }

                            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                                if (isSeekBarTouched) {
                                    val intent = Intent(this@SystemSongActivity, PlayService::class.java)
                                    intent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.SONG_ACTION_TYPE_SEEK_TO)
                                    intent.putExtra(PlayService.SONG_ACTION_TYPE_SEEK_KEY, seekBar?.progress)
                                    startForegroundService(intent)
                                    isSeekBarTouched = false
                                }
                            }
                        })

                        SongHelper.getInstance().addTimeProgressListener(this@SystemSongActivity)
                        break
                    }
                }
            }


            musicPause.setOnClickListener {
                if (SongHelper.getInstance().isPlaying) {
                    SongHelper.getInstance().pauseOrPlay(PlayService.SONG_ACTION_TYPE_PAUSE)
                    musicPause.setImageResource(R.mipmap.player_ic_play_blue)
                } else {
                    SongHelper.getInstance().pauseOrPlay(PlayService.SONG_ACTION_TYPE_CONTINUE)

                    musicPause.setImageResource(R.mipmap.player_ic_pause_blue)
                }
            }


            scanFile(this, filePath)


            backToList.setOnClickListener {
                startActivity(Intent(this, SongActivity::class.java))
                finish()
            }

//            Log.e("song", "filename is " + filePath)
//            if (SongHelper.getInstance()?.getList() != null) {
//                for ((index, item) in SongHelper.getInstance()?.getList()!!.withIndex()) {
//                    if (item.path == filePath) {
//                        val intent = Intent(this, SongActivity::class.java)
//                        intent.putExtra("songId", item.id)
//                        intent.putExtra("position", index)
//                        startActivity(intent)
//                        finish()
//                        break
//                    }
//
//                    //新歌曲
//                    val intent = Intent(this, SongActivity::class.java)
//                    intent.putExtra("path", filePath)
//                    startActivity(intent)
//                    finish()
//                }
//            } else {
//                //新歌曲
//                val intent = Intent(this, SongActivity::class.java)
//                intent.putExtra("path", filePath)
//                startActivity(intent)
//                finish()
//            }






//            if (String.valueOf(uri) != null && String.valueOf(uri).contains("content")) {
//                var kkk = false;
//                try{
//                    filename = CommonUtils.getFilePathFromContentUri(uri,this.getContentResolver());
//                    if(CommonUtils.isEmpty(filename)){
//                        kkk = true;
//                    }
//                }catch (e:Exception){
//                    e.printStackTrace();
//                    kkk = true;
//                }
//                if(kkk){
//                    filename = ProviderUtils.getFPUriToPath(this,uri);
//                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        SongHelper.getInstance().removeTimeProgressListener(this@SystemSongActivity)
    }


    /**
     * 针对系统文夹只需要扫描,不用插入内容提供者,不然会重复
     *
     * @param context  上下文
     * @param filePath 文件路径
     */
    private fun scanFile(context: Context, filePath: String?) {
        if (!File(filePath).exists())
            return
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        intent.data = Uri.fromFile(File(filePath))
        context.sendBroadcast(intent)
    }

    override fun onTimeChange(currentTime: Int) {
        if (currentTime >= musicProgress.max - 3) {//播放结束跳到列表页
            startActivity(Intent(this, SongActivity::class.java))
            finish()
            return
        }
        musicTime.text = SongUtils.formatTime(currentTime) + " / " + SongUtils.formatTime(musicProgress.max)
    }
}